package com.example.educationblockchain.controller;

import com.example.educationblockchain.util.AdminToken;
import com.example.educationblockchain.util.StudentToken;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@Controller
public class LoginController {

    @RequestMapping("/")
    public String index(){
        System.out.println("kk");
        return "../static/login";
    }

    @RequestMapping("/toLogin")
    public String toLogin(){
        System.out.println("login login");
        return "../static/login";
    }

    @RequestMapping("/adminLogin")
    @ResponseBody
    public String adminLogin(@RequestBody Map<String,Object> data){
        String id= data.get("adminId").toString();
        String password = data.get("adminPassword").toString();
        Subject subject = SecurityUtils.getSubject();
        // 创建token
        UsernamePasswordToken token = new AdminToken(id, password);
        // 执行登录方法，如果没有异常就说明登录了
        try {
            System.out.println("登录");
            subject.login(token);
            return "list";
        } catch (UnknownAccountException e) {
            return "unLogin";
        }catch (IncorrectCredentialsException e){
            return "unLogin";
        }
    }

    @RequestMapping("/studentLogin")
    @ResponseBody
    public String studentLogin(@RequestBody Map<String,Object> data){
        String id= data.get("studentId").toString();
        String password = data.get("studentPassword").toString();
        Subject subject = SecurityUtils.getSubject();
        // 创建token
        UsernamePasswordToken token = new StudentToken(id, password);
        // 执行登录方法，如果没有异常就说明登录了
        try {
            System.out.println("登录");
            subject.login(token);
            return "list";
        } catch (UnknownAccountException e) {
            return "unLogin";
        }catch (IncorrectCredentialsException e){
            return "unLogin";
        }
    }

    @RequestMapping("/logout")
    @ResponseBody
    public String logout() {
        System.out.println("退出");
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        System.out.println("退出登录");
        return "";
    };
}
